<template>
  <div class="home-container">
    <!-- 欢迎信息和日期 -->
    <div class="dashboard-header">
      <div class="welcome-section">
        <h1 class="welcome-title">欢迎回来，{{ username }}</h1>
        <div class="date-info">{{ today }} {{ weekday }}</div>
      </div>
      <div class="welcome-actions">
        <el-button type="primary" @click="refreshData" :loading="loading" size="small">
          <el-icon class="mr-5"><Refresh /></el-icon>刷新数据
        </el-button>
      </div>
    </div>
    
    <!-- 数据统计卡片 -->
    <div class="stat-row">
      <el-card class="stat-card" shadow="hover" :body-style="{padding: '0'}">
        <div class="stat-icon-bg" style="background-color: rgba(64, 158, 255, 0.1);">
          <el-icon><ShoppingCart /></el-icon>
        </div>
        <div class="stat-info">
          <h2 class="stat-value">{{ stats.orderCount }}</h2>
          <div class="stat-label">进行中的订单</div>
          <div class="stat-trend" :class="stats.orderTrend >= 0 ? 'up' : 'down'">
            <el-icon v-if="stats.orderTrend >= 0"><ArrowUp /></el-icon>
            <el-icon v-else><ArrowDown /></el-icon>
            <span>{{ Math.abs(stats.orderTrend).toFixed(1) }}%</span>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover" :body-style="{padding: '0'}">
        <div class="stat-icon-bg" style="background-color: rgba(103, 194, 58, 0.1);">
          <el-icon><Calendar /></el-icon>
        </div>
        <div class="stat-info">
          <h2 class="stat-value">{{ stats.appointmentCount }}</h2>
          <div class="stat-label">待处理预约</div>
          <div class="stat-trend" :class="stats.appointmentTrend >= 0 ? 'up' : 'down'">
            <el-icon v-if="stats.appointmentTrend >= 0"><ArrowUp /></el-icon>
            <el-icon v-else><ArrowDown /></el-icon>
            <span>{{ Math.abs(stats.appointmentTrend).toFixed(1) }}%</span>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover" :body-style="{padding: '0'}">
        <div class="stat-icon-bg" style="background-color: rgba(230, 162, 60, 0.1);">
          <el-icon><Star /></el-icon>
        </div>
        <div class="stat-info">
          <h2 class="stat-value">{{ stats.favoriteCount }}</h2>
          <div class="stat-label">收藏设计</div>
          <div class="stat-trend" :class="stats.favoriteTrend >= 0 ? 'up' : 'down'">
            <el-icon v-if="stats.favoriteTrend >= 0"><ArrowUp /></el-icon>
            <el-icon v-else><ArrowDown /></el-icon>
            <span>{{ Math.abs(stats.favoriteTrend).toFixed(1) }}%</span>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover" :body-style="{padding: '0'}">
        <div class="stat-icon-bg" style="background-color: rgba(245, 108, 108, 0.1);">
          <el-icon><ChatLineRound /></el-icon>
        </div>
        <div class="stat-info">
          <h2 class="stat-value">{{ stats.messageCount }}</h2>
          <div class="stat-label">未读消息</div>
          <div class="stat-trend" :class="stats.messageTrend >= 0 ? 'up' : 'down'">
            <el-icon v-if="stats.messageTrend >= 0"><ArrowUp /></el-icon>
            <el-icon v-else><ArrowDown /></el-icon>
            <span>{{ Math.abs(stats.messageTrend).toFixed(1) }}%</span>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 快捷入口 -->
    <div class="quick-access-section">
      <h2 class="section-title">快捷入口</h2>
      <div class="quick-access-row">
        <div 
          v-for="(item, index) in quickAccessItems" 
          :key="index" 
          class="quick-access-item" 
          @click="navigateTo(item.path)"
          :style="{animationDelay: index * 0.1 + 's'}"
        >
          <div class="quick-icon">
            <component :is="item.icon"></component>
          </div>
          <div class="quick-text">{{ item.title }}</div>
        </div>
      </div>
    </div>
    
    <!-- 数据卡片 -->
    <div class="data-row">
      <!-- 最近订单 -->
      <el-card class="data-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>最近订单</span>
            <el-button @click="navigateTo('/order/list')" text>查看全部</el-button>
          </div>
        </template>
        <div class="data-content">
          <el-table :data="recentOrders" style="width: 100%" v-loading="orderLoading">
            <el-table-column prop="orderNo" label="订单号" width="140" />
            <el-table-column prop="productName" label="产品名称" />
            <el-table-column prop="orderTime" label="下单时间" width="160" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getOrderStatusType(scope.row.status)">
                  {{ getOrderStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      
      <!-- 待处理预约 -->
      <el-card class="data-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>待处理预约</span>
            <el-button @click="navigateTo('/appointment/list')" text>查看全部</el-button>
          </div>
        </template>
        <div class="data-content">
          <el-table :data="pendingAppointments" style="width: 100%" v-loading="appointmentLoading">
            <el-table-column prop="appointmentNo" label="预约号" width="140" />
            <el-table-column prop="type" label="类型" width="100">
              <template #default="scope">
                <el-tag :type="getAppointmentTypeType(scope.row.type)">
                  {{ getAppointmentTypeText(scope.row.type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="designerName" label="设计师" />
            <el-table-column prop="appointmentTime" label="预约时间" width="160" />
          </el-table>
        </div>
      </el-card>
    </div>
    
    <!-- 推荐设计 -->
    <div class="recommendation-section">
      <h2 class="section-title">
        推荐设计
        <el-button @click="navigateTo('/design/works')" text>查看更多</el-button>
      </h2>
      <div class="design-list">
        <div v-for="design in recommendDesigns" :key="design.id" class="design-item" @click="viewDesignDetail(design)">
          <div class="design-cover">
            <el-image :src="design.coverUrl" fit="cover">
              <template #error>
                <div class="image-placeholder">
                  <el-icon><PictureIcon /></el-icon>
                </div>
              </template>
            </el-image>
            <div class="design-hover">
              <el-button type="primary" size="small" circle>
                <el-icon><ViewIcon /></el-icon>
              </el-button>
            </div>
          </div>
          <div class="design-info">
            <div class="design-title">{{ design.title }}</div>
            <div class="design-meta">
              <span>设计师: {{ design.designerName }}</span>
              <span><el-icon><Star /></el-icon> {{ design.likeCount }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 活动时间线 -->
    <div class="activity-section">
      <h2 class="section-title">近期活动</h2>
      <el-timeline v-loading="activityLoading">
        <el-timeline-item
          v-for="(activity, index) in recentActivities"
          :key="index"
          :color="activity.color"
          :timestamp="activity.time"
        >
          {{ activity.content }}
        </el-timeline-item>
      </el-timeline>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { 
  ShoppingCart, Calendar, Star, ChatLineRound, 
  ArrowUp, ArrowDown, Plus, ViewIcon, Edit, 
  Goods, Clock, Refresh, Setting, Picture as PictureIcon,
  Message, Wallet, User, Document
} from '@element-plus/icons-vue'
import { getHomeStats, getRecentOrders, getPendingAppointments, getRecommendDesigns, getRecentActivities } from '@/api/home'

export default {
  name: 'Home',
  components: {
    ShoppingCart, Calendar, Star, ChatLineRound, 
    ArrowUp, ArrowDown, Plus, ViewIcon, Edit, 
    Goods, Clock, Refresh, Setting, PictureIcon,
    Message, Wallet, User, Document
  },
  setup() {
    const router = useRouter()
    const username = ref(localStorage.getItem('username') || '用户')
    const loading = ref(false)
    const orderLoading = ref(false)
    const appointmentLoading = ref(false)
    const designLoading = ref(false)
    const activityLoading = ref(false)
    
    // 今天日期
    const today = computed(() => {
      const date = new Date()
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
    })
    
    // 星期几
    const weekday = computed(() => {
      const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
      return weekdays[new Date().getDay()]
    })
    
    // 统计数据
    const stats = reactive({
      orderCount: 0,
      orderTrend: 0,
      appointmentCount: 0,
      appointmentTrend: 0,
      favoriteCount: 0,
      favoriteTrend: 0,
      messageCount: 0,
      messageTrend: 0
    })
    
    // 快捷入口
    const quickAccessItems = [
      { title: '提交定制', icon: 'Plus', path: '/custom/submit' },
      { title: '预约设计师', icon: 'Calendar', path: '/appointment/new' },
      { title: '我的订单', icon: 'Document', path: '/order/list' },
      { title: '我的定制', icon: 'Goods', path: '/custom/list' },
      { title: '设计师作品', icon: 'Star', path: '/design/works' },
      { title: '消息中心', icon: 'Message', path: '/message' },
      { title: '个人中心', icon: 'User', path: '/user' },
      { title: '系统设置', icon: 'Setting', path: '/user/settings' }
    ]
    
    // 数据列表
    const recentOrders = ref([])
    const pendingAppointments = ref([])
    const recommendDesigns = ref([])
    const recentActivities = ref([])
    
    // 获取首页统计数据
    const fetchHomeStats = async () => {
      try {
        loading.value = true
        const res = await getHomeStats()
        Object.assign(stats, res.data)
      } catch (error) {
        console.error('获取统计数据失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 获取最近订单
    const fetchRecentOrders = async () => {
      try {
        orderLoading.value = true
        const res = await getRecentOrders()
        recentOrders.value = res.data
      } catch (error) {
        console.error('获取最近订单失败:', error)
      } finally {
        orderLoading.value = false
      }
    }
    
    // 获取待处理预约
    const fetchPendingAppointments = async () => {
      try {
        appointmentLoading.value = true
        const res = await getPendingAppointments()
        pendingAppointments.value = res.data
      } catch (error) {
        console.error('获取待处理预约失败:', error)
      } finally {
        appointmentLoading.value = false
      }
    }
    
    // 获取推荐设计
    const fetchRecommendDesigns = async () => {
      try {
        designLoading.value = true
        const res = await getRecommendDesigns()
        recommendDesigns.value = res.data
      } catch (error) {
        console.error('获取推荐设计失败:', error)
      } finally {
        designLoading.value = false
      }
    }
    
    // 获取近期活动
    const fetchRecentActivities = async () => {
      try {
        activityLoading.value = true
        const res = await getRecentActivities()
        recentActivities.value = res.data
      } catch (error) {
        console.error('获取近期活动失败:', error)
      } finally {
        activityLoading.value = false
      }
    }
    
    // 刷新所有数据
    const refreshData = () => {
      fetchHomeStats()
      fetchRecentOrders()
      fetchPendingAppointments()
      fetchRecommendDesigns()
      fetchRecentActivities()
    }
    
    // 获取订单状态类型
    const getOrderStatusType = (status) => {
      const statusMap = {
        'PENDING_PAYMENT': 'warning',
        'PENDING_DELIVERY': 'info', 
        'IN_PRODUCTION': 'primary',
        'SHIPPED': 'success',
        'COMPLETED': 'success',
        'CANCELLED': 'info'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取订单状态文本
    const getOrderStatusText = (status) => {
      const statusMap = {
        'PENDING_PAYMENT': '待付款',
        'PENDING_DELIVERY': '待发货', 
        'IN_PRODUCTION': '生产中',
        'SHIPPED': '已发货',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    }
    
    // 获取预约类型类型
    const getAppointmentTypeType = (type) => {
      const typeMap = {
        'MEASUREMENT': 'success',
        'DESIGN_CONSULTATION': 'primary',
        'FITTING': 'warning',
        'GENERAL_CONSULTATION': 'info'
      }
      return typeMap[type] || 'info'
    }
    
    // 获取预约类型文本
    const getAppointmentTypeText = (type) => {
      const typeMap = {
        'MEASUREMENT': '量体',
        'DESIGN_CONSULTATION': '设计咨询',
        'FITTING': '试衣',
        'GENERAL_CONSULTATION': '通用咨询'
      }
      return typeMap[type] || type
    }
    
    // 导航到指定路径
    const navigateTo = (path) => {
      router.push(path)
    }
    
    // 查看设计详情
    const viewDesignDetail = (design) => {
      router.push(`/design/detail/${design.id}`)
    }
    
    // 初始化
    onMounted(() => {
      fetchHomeStats()
      fetchRecentOrders()
      fetchPendingAppointments()
      fetchRecommendDesigns()
      fetchRecentActivities()
    })
    
    return {
      username,
      today,
      weekday,
      stats,
      quickAccessItems,
      recentOrders,
      pendingAppointments,
      recommendDesigns,
      recentActivities,
      getOrderStatusType,
      getOrderStatusText,
      getAppointmentTypeType,
      getAppointmentTypeText,
      navigateTo,
      viewDesignDetail,
      loading,
      orderLoading,
      appointmentLoading,
      designLoading,
      activityLoading,
      refreshData
    }
  }
}
</script>

<style scoped>
.home-container {
  padding: 20px;
  box-sizing: border-box;
  min-height: calc(100vh - 60px);
  background-color: var(--page-background);
  width: 100%;
  max-width: 1920px;
  margin: 0 auto;
}

.dashboard-header {
  margin-bottom: 24px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
}

.welcome-title {
  font-size: clamp(20px, 2vw, 24px);
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--heading-color);
}

.date-info {
  font-size: clamp(12px, 1.2vw, 14px);
  color: var(--text-color-secondary);
}

.section-title {
  margin-bottom: 16px;
  font-size: clamp(16px, 1.8vw, 18px);
  font-weight: 500;
  color: var(--heading-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 数据统计卡片 */
.stat-row {
  margin-bottom: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.stat-card {
  height: auto;
  min-height: 120px;
  overflow: hidden;
  display: flex;
  position: relative;
  transition: transform 0.3s;
  border-radius: 8px;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.stat-icon-bg {
  position: absolute;
  width: clamp(80px, 10vw, 120px);
  height: clamp(80px, 10vw, 120px);
  border-radius: 50%;
  right: -20px;
  top: -20px;
  opacity: 0.2;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: clamp(40px, 5vw, 60px);
}

.stat-info {
  padding: clamp(12px, 1.5vw, 20px);
  display: flex;
  flex-direction: column;
  justify-content: center;
  flex: 1;
}

.stat-value {
  font-size: clamp(24px, 3vw, 32px);
  font-weight: bold;
  margin-bottom: 4px;
  color: var(--heading-color);
  margin-top: 0;
}

.stat-label {
  font-size: clamp(12px, 1.2vw, 14px);
  color: var(--text-color-secondary);
  margin-bottom: 8px;
}

.stat-trend {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.stat-trend.up {
  color: #67C23A;
}

.stat-trend.down {
  color: #F56C6C;
}

.stat-trend .el-icon {
  margin-right: 4px;
}

/* 快捷入口 */
.quick-access-section {
  margin-bottom: 24px;
}

.quick-access-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.quick-access-item {
  background-color: var(--component-background);
  border-radius: 8px;
  padding: clamp(12px, 1.5vw, 16px);
  text-align: center;
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  height: auto;
  min-height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 12px 0 var(--shadow-color);
  animation: fadeInUp 0.5s ease-out forwards;
  opacity: 0;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.quick-access-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.quick-icon {
  font-size: clamp(20px, 2.5vw, 28px);
  margin-bottom: 8px;
  color: var(--primary-color);
}

.quick-text {
  font-size: clamp(12px, 1.2vw, 14px);
  color: var(--text-color);
}

/* 数据卡片 */
.data-row {
  margin-bottom: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.data-card {
  margin-bottom: 0;
  height: 100%;
  border-radius: 8px;
  transition: transform 0.3s, box-shadow 0.3s;
}

.data-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: clamp(8px, 1vw, 12px);
}

.data-content {
  min-height: 200px;
  padding: clamp(8px, 1vw, 12px);
}

/* 设计列表 */
.recommendation-section {
  margin-bottom: 24px;
}

.design-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: clamp(12px, 1.5vw, 16px);
  margin-top: 16px;
}

.design-item {
  background-color: var(--component-background);
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 var(--shadow-color);
  transition: transform 0.3s, box-shadow 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
  cursor: pointer;
}

.design-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.design-item:hover .design-hover {
  opacity: 1;
}

.design-cover {
  height: clamp(180px, 25vw, 250px);
  overflow: hidden;
  position: relative;
  cursor: pointer;
}

.design-hover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.design-info {
  padding: clamp(8px, 1vw, 12px);
  flex: 1;
}

.design-title {
  font-size: clamp(14px, 1.5vw, 16px);
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--heading-color);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.design-meta {
  display: flex;
  justify-content: space-between;
  font-size: clamp(10px, 1vw, 12px);
  color: var(--text-color-secondary);
}

.image-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
  color: #999;
  font-size: 32px;
}

/* 活动时间线 */
.activity-section {
  margin-bottom: 24px;
}

/* 响应式表格 */
:deep(.el-table) {
  font-size: clamp(12px, 1.2vw, 14px);
}

:deep(.el-table th) {
  padding: clamp(8px, 1vw, 12px);
}

:deep(.el-table td) {
  padding: clamp(8px, 1vw, 12px);
}

/* 时间线 */
:deep(.el-timeline-item__content) {
  font-size: clamp(12px, 1.2vw, 14px);
}

:deep(.el-timeline-item__timestamp) {
  font-size: clamp(10px, 1vw, 12px);
}

/* 按钮 */
:deep(.el-button) {
  padding: clamp(6px, 0.8vw, 8px) clamp(12px, 1.5vw, 16px);
  font-size: clamp(12px, 1.2vw, 14px);
}

/* 标签 */
:deep(.el-tag) {
  padding: clamp(4px, 0.5vw, 6px) clamp(8px, 1vw, 12px);
  font-size: clamp(10px, 1vw, 12px);
}

/* 图片 */
:deep(.el-image) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 媒体查询 */
@media (max-width: 768px) {
  .home-container {
    padding: 12px;
  }
  
  .stat-row {
    grid-template-columns: 1fr;
  }
  
  .data-row {
    grid-template-columns: 1fr;
  }
  
  .design-list {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  }
  
  .quick-access-row {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .quick-access-row {
    grid-template-columns: 1fr;
  }
  
  .design-list {
    grid-template-columns: 1fr;
  }
}
</style> 
  font-size: clamp(12px, 1.2vw, 14px);
}

:deep(.el-table th) {
  padding: clamp(8px, 1vw, 12px);
}

:deep(.el-table td) {
  padding: clamp(8px, 1vw, 12px);
}

/* 时间线 */
:deep(.el-timeline-item__content) {
  font-size: clamp(12px, 1.2vw, 14px);
}

:deep(.el-timeline-item__timestamp) {
  font-size: clamp(10px, 1vw, 12px);
}

/* 按钮 */
:deep(.el-button) {
  padding: clamp(6px, 0.8vw, 8px) clamp(12px, 1.5vw, 16px);
  font-size: clamp(12px, 1.2vw, 14px);
}

/* 标签 */
:deep(.el-tag) {
  padding: clamp(4px, 0.5vw, 6px) clamp(8px, 1vw, 12px);
  font-size: clamp(10px, 1vw, 12px);
}

/* 图片 */
:deep(.el-image) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 媒体查询 */
@media (max-width: 768px) {
  .home-container {
    padding: 12px;
  }
  
  .stat-row {
    grid-template-columns: 1fr;
  }
  
  .data-row {
    grid-template-columns: 1fr;
  }
  
  .design-list {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  }
  
  .quick-access-row {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .quick-access-row {
    grid-template-columns: 1fr;
  }
  
  .design-list {
    grid-template-columns: 1fr;
  }
}
</style> 